/**  
 * All rights Reserved, Designed By www.tydic.com
 * @Title:  OrderController.java   
 * @Package com.axin.controller   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: axin     
 * @date:   2019年4月9日 下午11:16:20   
 * @version V1.0 
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
package com.axin.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.axin.common.conf.Config;
import com.axin.common.entity.ApiToken;
import com.axin.common.entity.JsonResult;
import com.axin.common.entity.request.CreateOrderRequest;
import com.axin.common.entity.request.IntrustOrdersDetailRequest;
import com.axin.common.entity.response.Accounts;
import com.axin.common.entity.response.IntrustDetail;
import com.axin.common.entity.response.MatchresultsOrdersDetail;
import com.axin.common.entity.response.Merged;
import com.axin.common.entity.response.OrdersDetail;
import com.axin.common.exception.AccountLockException;
import com.axin.common.exception.ApiException;
import com.axin.common.utils.JobUtil;
import com.axin.service.AccountService;
import com.axin.service.MarketService;
import com.axin.service.OrderService;

/**   
 * @Description: TODO 
 * @ClassName:  OrderController
 * @author:  Axin 
 * @date:   2019年4月9日 下午11:16:20   
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
@Controller
@RequestMapping("/order")
public class OrderController {
	
	
	@Autowired
	private AccountService accountService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private MarketService marketService;
	
	
	@RequestMapping(value="/create",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult createOrder(HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		try {
			List<Accounts> accounts = accountService.getAccounts(token);
			if(CollectionUtils.isEmpty(accounts)){
				return new JsonResult(new RuntimeException("账户查询结果为空。"));
			}

			Integer accountId = null;
			for (Accounts account : accounts) {
				String type = account.getType();
				if("spot".equals(type)){
					accountId = account.getId();
					break;
				}
			}
			if(accountId==null)
				return new JsonResult(new RuntimeException("未找到账户id"));
			
			Map<String,String> map = new HashMap();
			 map.put("symbol", "bttusdt");
			Merged merged = marketService.getDetailMerged(token, map);
			if(merged==null){
				return new JsonResult(new RuntimeException("价格获取失败"));
			}
			double price = merged.getClose();
			BigDecimal p = new BigDecimal(price);
			String plainString = p.setScale(8, BigDecimal.ROUND_HALF_UP).toPlainString();
			
			 CreateOrderRequest createOrderReq = new CreateOrderRequest();
	         createOrderReq.accountId = String.valueOf(accountId);
	         createOrderReq.amount = "50";
	         createOrderReq.price = plainString;
	         createOrderReq.symbol = "bttusdt";
	         createOrderReq.type = CreateOrderRequest.OrderType.BUY_LIMIT;
	         createOrderReq.source = "api";
			/**29365789083*/
			Long orderId = this.orderService.createOrder(token, createOrderReq);
			System.out.println("===============订单号:"+orderId);
			if(orderId!=null){
				OrdersDetail ordersDetail = this.orderService.ordersDetail(token, orderId);
				return new JsonResult(ordersDetail);
			}else{
				return new JsonResult(new RuntimeException("下单失败"));
			}
		
			
		} catch (ApiException e) {
			e.printStackTrace();
			return new JsonResult(e);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(e);
		}
		
		
	}
	
	
	/**
	 * 查询某个订单详情
	 * @Description: TODO  
	 * @Title: ordersDetail   
	 * @param request
	 * @param orderId
	 * @return JsonResult
	 * @throws
	 */
	@RequestMapping(value="/ordersDetail",method=RequestMethod.GET)
	@ResponseBody
	public JsonResult ordersDetail(@RequestParam(value="orderId",required=true)Long orderId,
								HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		OrdersDetail ordersDetail = this.orderService.ordersDetail(token, orderId);
		return new JsonResult(ordersDetail);
	}
	
	/**
	 * 查询某个订单的成交明细
	 * @Description: TODO  
	 * @Title: matchresults   
	 * @param request
	 * @param orderId
	 * @return JsonResult
	 * @throws
	 */
	@RequestMapping(value="/matchresults",method=RequestMethod.GET)
	@ResponseBody
	public JsonResult matchresults(@RequestParam(value="orderId",required=true)Long orderId,
									HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		List<MatchresultsOrdersDetail> matchresults = this.orderService.matchresults(token, orderId);
		return new JsonResult(matchresults);
	}
	
	
	/**
	 * 查询当前委托、历史委托
	 * @Title: getOrders   
	 * @param entity
	 * @param request
	 * @return JsonResult
	 * @throws
	 */
	@RequestMapping(value="/getOrders",method=RequestMethod.GET)
	@ResponseBody
	public JsonResult getOrders(IntrustOrdersDetailRequest entity,
									HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		List<IntrustDetail> orders = this.orderService.getOrders(token, entity);
		return new JsonResult(orders);
	}
	
	@RequestMapping(value="/sell",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult sell(HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		try {
			Integer accountId = this.accountService.getAccountsByType(token, AccountService.TYPE_SPOT);
			Long orderId = this.orderService.createSellOrder(token, "bttusdt", accountId, 100+"");
			OrdersDetail ordersDetail = this.orderService.ordersDetail(token, orderId);
			return new JsonResult(ordersDetail);
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (AccountLockException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new JsonResult();
	}
	
	
	@RequestMapping(value="/buy",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult buy(HttpServletRequest request){
		ApiToken token = (ApiToken)request.getAttribute("apiToken");
		if(token == null){
			return new JsonResult(new RuntimeException("您尚未设置密钥，不能处理您的请求！"));
		}
		try {
			Integer accountId = this.accountService.getAccountsByType(token, AccountService.TYPE_SPOT);
			Long orderId = this.orderService.createBuyOrder(token, "bttusdt", accountId, 1.2+"");
			OrdersDetail ordersDetail = this.orderService.ordersDetail(token, orderId);
			return new JsonResult(ordersDetail);
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (AccountLockException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new JsonResult();
	}
	
	
	public static void main(String[] args) {
		BigDecimal money = new BigDecimal("1.199999999999999994");
		BigDecimal amount = new BigDecimal("1634");
		BigDecimal result = money.divide(amount,8,BigDecimal.ROUND_DOWN);
		System.out.println("单位价格:"+result.toPlainString());
		Config config = new Config();
		String[] positions = JobUtil.getPositions(result.toPlainString(), "5", 5, 8);
		for (int i = 0; i < positions.length; i++) {
			System.out.println(positions[i]);
		}
		
		BigDecimal b = new BigDecimal("0.00071299");
		BigDecimal c = new BigDecimal("0.00071268");
		BigDecimal d = b.subtract(c);
		BigDecimal divide = d.divide(b,4,BigDecimal.ROUND_HALF_UP);
		System.out.println(divide.toPlainString());
		
		
		
	}
	
	
	
	

}
